# Regular Expressions
# External interfaces: auto, generate
#
# There's a Regexp::Trie file in
# >>> https://gist.github.com/atiking/7525326
# But of little use


import re
import random
import string



def _mark(char):
    '''
    Mark the character with flags like
    - D/d: (non-)digits
    - W/w: (non-)word-char
    - S/s: (non-)space
    - v: special
    - x: beyound-ascii

    :param char(str/bytes of length 1)
    :rtype sequence of flags

    exmples:
    >>> _mark('1')   #=> 'dwS'
    >>> _mark('C')   #=> 'DwS'
    >>> _mark('\\t') #=> 'DWs'
    >>> _mark('#')   #=> 'DWS'
    '''
    if char in string.digits:
        return 'dwS'
    elif char in string.ascii_letters:
        return 'DwS'
    elif char in string.whitespace:
        return 'DWs'
    else:
        return 'DWS'


def _compress(flags):
    '''
    Compress flags into groups.

    :param flags(sequence of str)
    :rtype list of (flags, count) pairs

    examples:
    >>> ['DwS', 'DwS', 'DwS', 'DwS', 'DwS', 'DwS']
    #=> [('DwS', 6)]
    >>> ['dwS', 'dwS', 'DwS', 'DwS', 'DwS', 'DwS']
    #=> [('dwS', 2), ('DwS', 4)]
    '''
    cur = flags[0]
    cnt = 0
    result = []
    for flag in flags:
        if flag == cur:
            cnt += 1
        else:
            result.append((cur, cnt))
            cur = flag
            cnt = 1
    return result + [(cur, cnt)]


def _group(string):
    '''
    Split string into groups by continuance.

    :param string(str)
    :rtype groups of patterns(sequence)

    examples:
    >>> _group('abcdef')  #=> [('DwS', 6)]
    >>> _group('12abAB')  #=> [('dwS', 2), ('DwS', 4)]
    >>> _group('2016-01-23')
    #=> [('dwS', 4), (DWS', 1), ('dwS', 2), ('DWS', 1), ('dwS', 2)]
    '''
    return _compress([_mark(c) for c in string])


def _intersection(s, t):
    '''
    Calculate the intersection of two strings(flags)

    :param s, t(str)
    :rtype str

    examples:
    >>> _intersection('dwS', 'DwS')
    #=> 'wS'
    >>> _intersection('dwS', 'DWS')
    #=> 'S'
    >>> _intersection('dwS', 'DWs')
    #=> ''
    '''
    return ''.join([c for c in s if c in t])


def _aggregate(groups):
    '''
    **TODO**

    Be careful when dealing with 'DWS' !!

    :param groups(sequence of (flags, count) pairs)

    examples:
    >>> [('dwS', 2), ('DwS', 4)]  # , ('DWs')]
    #=> [('wS', 6)]
    '''
    pass


def _transform():
    pass


def auto(*strings, **kwargs):
    '''
    Extract a regexp pattern automatically from the source strings.

    :param strings(*args of str)
    :param kwargs(**kwargs)
    :rtype regexp-pattern(str/pattern)

    examples:
    >>> auto('abc', 'def', '123')
    #=> r'\w{3}'  # '\\\\w{3}'
    '''
    pass


def generate(pattern):
    '''
    Generate a string that matches the regular expression ``pattern``.
    :param pattern(str) a regexp type string
    :rtype generated-string(str)
    '''
    pass
